import 'package:flutter/material.dart';
import 'package:super_tool_server/component/clickable/clickable_widget.dart';
import 'package:super_tool_server/component/image/image_view.dart';
import 'package:super_tool_server/component/theme/theme.dart';

class ImageViewItem {
  ImageViewItem({this.id, this.url});

  final String? id;
  final String? url;
}

enum ImageViewListStyle { gridStyle, wrapStyle }

/// 图片列表
class ImageViewList extends StatelessWidget {
  ImageViewList(
      {required this.imageList,
      this.onDeleted,
      this.canDelete = false,
      this.style = ImageViewListStyle.gridStyle});

  /// 要展示的图片资源列表
  final List<ImageViewItem> imageList;

  /// 删除回调
  final Function? onDeleted;

  /// 图片能否删除
  final bool canDelete;

  /// 布局方式(GridLayout 或者 WrapImage)
  final ImageViewListStyle style;

  Widget _buildImageItem(context, item, index) {
    return Stack(
      children: [
        ClickableWidget(builder: (context, _) {
          return ImageViewWidget.network(imageUrl: imageList[index].url ?? '');
        }),
        if (canDelete)
          Positioned(
            right: 20,
            top: 0,
            child: Container(
              color: Colors.black.withOpacity(0.5),
              padding: EdgeInsets.all(5),
              child: ClickableWidget(
                onTap: () {
                  onDeleted!(index, imageList[index]);
                },
                builder: (context, _) {
                  return Icon(
                    Icons.close,
                    size: 10,
                    color: CustomTheme.of(context)!.colors.background.light,
                  );
                },
              ),
            ),
          )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if (imageList.isEmpty) {
      return Container();
    }
    if (style == ImageViewListStyle.wrapStyle) {
      return Wrap(
        children: imageList.asMap().keys.map((index) {
          return _buildImageItem(context, imageList[index], index);
        }).toList(),
      );
    }
    return GridView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: imageList.length,
      padding: EdgeInsets.only(top: 15),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, mainAxisSpacing: 3, crossAxisSpacing: 3),
      itemBuilder: (context, index) {
        return _buildImageItem(context, imageList[index], index);
      },
    );
  }
}
